package com.csw.shuanfa.CodeImprove.redlockThread.locktest.service.impl;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class DateBaseComponentImpl {


    @Autowired
    private RedissonClient redissonClient;

    //private  RedissonClient redissonClient = BloomRedLock.getRedissonClient();
    // 模拟数据库的数据
    public volatile int num = 2;

    // 模拟修改数据库的数据
    //SynchronizedService
    public void synchronizedDecrment() {
        synchronized ("1".intern()) {//锁什么对象
            try {
                if (num > 0) {
                    // 模拟查库时间
                    Thread.sleep(100);
                    //TimeUnit.SECONDS.sleep(5);
                    num--;
                    System.out.println(num);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 详细实现参照redis-aop项目
     * RedLockService
     */
    public void redLockDecrment() {//默认锁失效时间是30s,
        // 获取锁
        RLock lock = redissonClient.getLock("REDLOCK_KEY");
        try {
            //500ms拿不到锁, 就认为获取锁失败。10000ms即10s是锁失效时间。
            boolean b = lock.tryLock(1 * 60 * 1000, 1 * 60 * 1000, TimeUnit.MILLISECONDS);
            if (b) {
                if (num > 0) {
                    // 模拟查库时间
                    Thread.sleep(10);//2*100  》10+第一次加锁时间
                    //TimeUnit.SECONDS.sleep(5);
                    num--;
                    System.out.println("结果是】" + num);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }


    //SingleService
    public void decrment() {
        try {
            if (num > 0) {
                // 模拟查库时间
                Thread.sleep(100);
                //TimeUnit.SECONDS.sleep(5);
                num--;
                System.out.println(num);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
